<template>
  <Form
      ref="formRef"
      v-model="initFormData"
      :model="formState"
      class="md:flex-row w-full flex-wrap"
      v-bind="formItemLayout"
  >
    <div class="md:flex w-full md:justify-between">
      <Col :span="6">
        <FormItem label="应用" name="stepType" style="width: 220px">
          <div class="md:w-30">
            <Select
                v-model:value="appId"
                :allowClear="true"
                :options="appOptions"
                placeholder="请选择应用"
            >
            </Select>
          </div>
        </FormItem>
      </Col>
      <Col :span="5">
        <FormItem label="步长" name="stepType" style="width: 185px">
          <div class="md:w-20">
            <Select
                v-model:value="step"
                :allowClear="true"
                :options="stepType"
                @change="onSelectChange"
            >
            </Select>
          </div>
        </FormItem>
      </Col>
      <Col :span="10">
        <FormItem label="时间" name="time" style="width: 300px">
          <div class="md:flex">
            <div class="md:w-28">
              <DatePicker
                  v-model:value="startValue"
                  :disabled="pickerDisabled"
                  :disabled-date="disabledStartDate"
                  :format="format"
                  :open="startOpenShow"
                  :picker="mode"
                  :placeholder="startPlaceholder"
                  @openChange="handleStartOpenChange"
                  @panelChange="handleStartPanelChange"
              />
            </div>
            <span> ~ </span>
            <div class="md:w-28">
              <DatePicker
                  v-model:value="endValue"
                  :disabled="pickerDisabled"
                  :disabled-date="disabledEndDate"
                  :format="format"
                  :open="endOpenShow"
                  :picker="mode"
                  :placeholder="endPlaceholder"
                  @openChange="handleEndOpenChange"
                  @panelChange="handleEndPanelChange"
              />
            </div>
          </div>
        </FormItem>
      </Col>
      <Col :span="3">
        <FormItem>
          <div class="md:flex md:justify-end">
            <Button shape="circle" type="primary" @click="onSubmit">
              <template #icon>
                <SearchOutlined/>
              </template>
            </Button>
            <Button shape="circle" style="margin-left: 5px" @click="resetForm">
              <template #icon>
                <RedoOutlined/>
              </template>
            </Button>
          </div>
        </FormItem>
      </Col>
    </div>
  </Form>
</template>

<script lang="ts" setup>
import {computed, onMounted, reactive, ref} from 'vue';
import {Moment} from 'moment';
import {Button, Col, DatePicker, Form, FormItem, Select,} from 'ant-design-vue';
import {RedoOutlined, SearchOutlined} from '@ant-design/icons-vue';
import {AppTemplateResp} from '/@/api/operation-center/common/model/commonModel';
import {getAppSelectList} from '/@/api/operation-center/common/common';
import {
  AppSubAnalysisInTotalReq
} from '/@/api/operation-center/tenant-opertation/app-subscription-analysis/model/appSubscriptionModel';


const props = defineProps({
  stepConfig: String,
  initData: Object,
})

let initFormData = computed(() => props.initData);

const formRef = ref();

const formState = reactive<Record<string, any>>({});

const formItemLayout = {
  labelCol: {span: 5},
  wrapperCol: {span: 24},
};

// Select 组件属性设置
const appId = ref();
const appOptions = ref<any[]>([]);

const step = ref();
const stepType = ref([]);

const stepValue = ref([0, 1]);

const startValue = ref<Moment | undefined>();
const startPlaceholder = ref<string>('开始月份');
const startOpenShow = ref<boolean>(false);
const endValue = ref<Moment>();
const endPlaceholder = ref<string>('结束月份');
const endOpenShow = ref<boolean>(false);
const format = ref<string>('YYYY-MM');
const pickerDisabled = ref<boolean>(true);
const mode = ref('month');
const emits = defineEmits(['success']);

const onSelectChange = (val) => {
  if (typeof val == 'undefined') {
    pickerDisabled.value = true;
  } else if (val !== 0 && !val) {
    pickerDisabled.value = true;
  } else if (stepValue.value.indexOf(val) < 0) {
    pickerDisabled.value = true;
  }
  if (props.stepConfig === 'tenant-app-sub-total') {
    if (val === 0) {
      pickerDisabled.value = false;
      startPlaceholder.value = '开始月份';
      endPlaceholder.value = '结束月份';
      mode.value = 'month';
      format.value = 'YYYY-MM';
    } else if (val === 1) {
      pickerDisabled.value = false;
      startPlaceholder.value = '开始年份';
      endPlaceholder.value = '结束年份';
      mode.value = 'year';
      format.value = 'YYYY';
    }
  } else if (props.stepConfig === 'app-active-users-in-total' || props.stepConfig === 'average-function-clicks') {
    if (val === 0) {
      pickerDisabled.value = false;
      startPlaceholder.value = '开始年份';
      endPlaceholder.value = '结束年份';
      mode.value = 'year';
      format.value = 'YYYY';
    } else if (val === 1) {
      pickerDisabled.value = false;
      startPlaceholder.value = '开始月份';
      endPlaceholder.value = '结束月份';
      mode.value = 'month';
      format.value = 'YYYY-MM';
    } else if (val === 2) {
      pickerDisabled.value = false;
      startPlaceholder.value = '开始周';
      endPlaceholder.value = '结束周';
      mode.value = 'week';
      format.value = 'YYYY-MM-DD';
    } else if (val === 3) {
      pickerDisabled.value = false;
      startPlaceholder.value = '开始日期';
      endPlaceholder.value = '结束日期';
      mode.value = 'date';
      format.value = 'YYYY-MM-DD';
    }
  }
};

const disabledStartDate = (startValue: Moment) => {
  if (!startValue || !endValue.value) {
    return false;
  }
  return startValue.valueOf() > endValue.value.valueOf();
};

const disabledEndDate = (endValue: Moment) => {
  if (!endValue || !startValue.value) {
    return false;
  }
  return startValue.value.valueOf() >= endValue.valueOf();
};

const handleStartOpenChange = (open: boolean) => {
  if (!open) {
    endOpenShow.value = true;
    startOpenShow.value = false;
  } else {
    startOpenShow.value = true;
  }
};

const handleEndOpenChange = (open: boolean) => {
  endOpenShow.value = open;
};

const handleStartPanelChange = (value) => {
  startValue.value = value;
  startOpenShow.value = false;
};

const handleEndPanelChange = (value) => {
  endValue.value = value;
  endOpenShow.value = false;
};

// 提交表单参数
const onSubmit = async () => {
  formRef.value.validate().then(() => {

    let appSubAnalysisInTotalReq: AppSubAnalysisInTotalReq = {
      appId: appId.value,
      stepType: step.value,
      startTime: startValue.value.format('YYYY-MM-DD HH:mm:ss'),
      endTime: endValue.value.format('YYYY-MM-DD HH:mm:ss'),
    };

    emits('success', appSubAnalysisInTotalReq);
  });
};

// 清空表单参数
const resetForm = () => {
  appId.value = undefined;
  step.value = undefined;
  startValue.value = undefined;
  endValue.value = undefined;
  pickerDisabled.value = true;
};

onMounted(() => {

  if (props.stepConfig === 'tenant-app-sub-total') {
    stepType.value = [
      {label: '按月', value: 0},
      {label: '按年', value: 1},
    ];
    stepValue.value = [0, 1];
  } else if (props.stepConfig === 'app-active-users-in-total' || props.stepConfig === 'average-function-clicks') {
    stepType.value = [
      {label: '按年', value: 0},
      {label: '按月', value: 1},
      {label: '按周', value: 2},
      {label: '按日', value: 3},
    ];
    stepValue.value = [0, 1, 2, 3];
  }

  function convertAppOptions(res: AppTemplateResp[]) {
    let options: any[] = [];
    for (let i = 0; i < res.length; i++) {
      let appItem = res[i];
      let appOption = {
        label: appItem.name,
        value: appItem.id,
      };
      options.push(appOption);
    }
    appOptions.value = options;
  }

  getAppSelectList().then((res) => {

    // 转换App选项为下拉框要求的标准格式
    convertAppOptions(res);
  });
});

</script>
